package org.jypj.dev.controller;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jypj.dev.dao.*;
import org.jypj.dev.vo.indexVo.IRoad;
import org.jypj.dev.vo.indexVo.ITrainUserWork;
import org.jypj.dev.model.*;
import org.jypj.dev.service.*;
import org.jypj.dev.util.*;
import org.jypj.dev.vo.*;
import org.jypj.dev.vo.indexVo.IUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 首页-巡检检测
 *
 * @author chenyu
 */
@Controller
@RequestMapping(value = "indexController")
public class IndexController extends BaseController {

    @Resource
    private IRoadService roadService;
    @Resource
    private IIndexDao indexDao;

    @Resource
    private IIndexService indexService;
    @Resource
    private IUserTrainScoreDao userTrainScoreDao;

    @Resource
    private IUserWorkFileService userWorkFileService;

    @Resource
    private ICodeDataService codeDataService;

    @Resource
    private ErrorWorkDao errorWorkDao;

    /**
     * 跳转到首页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "toIndex.action")
    public String toIndex(HttpServletRequest request) {
        String todayString = DateUtils.getTodayString("yyyy-MM-dd");
        request.setAttribute("today", todayString);

        return "back/bus/index_main";
    }

    /**
     * 查询异常工序信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllErrorWork.action")
    public Map<String, Object> selectAllErrorWork() {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            String todayString = DateUtils.getTodayString("yyyy-MM-dd");
            queryMap.put("planDate", todayString);
            List<ErrorWork> errorWorks = errorWorkDao.selectAllByMap(queryMap);
            dataMap.put("data", errorWorks);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 查询搜索数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("selectSearchData.action")
    public List<IRoad> selectSearchData(SearchVo searchVo) {
        List<IRoad> iRoads = indexService.selectAllRoads(searchVo);
        return iRoads;
    }

    /**
     * 跳转到文件上传页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "toFileList.action")
    public String toFileList(HttpServletRequest request, String trainCode, String loginId) {
        String fileServerUrl = IpUtil.getFileServerUrl(request);
        LoginInfo loginInfo = getLoginInfo(loginId);
        Road road = roadService.selectRoadById(loginInfo.getRoadId());
        List<Train> trains = road.getTrains();
        for (Train train : trains) {
            if (trainCode.equals(train.getCode())) {
                request.setAttribute("train", train);
            }
        }
        request.setAttribute("loginInfo", loginInfo);
        request.setAttribute("road", road);
        request.setAttribute("fileServerUrl", fileServerUrl);
        return "back/bus/index_file_list";
    }

    /**
     * 下载交路文件
     *
     * @param roadId
     */
    @RequestMapping("downLoadFile.action")
    @ResponseBody
    public int downLoadFile(String roadId, String planDate, HttpServletResponse response) {
        String basePath = PropertyUtil.getProperties("file_path");
        String workFileTableNameFromDate = StringUtil.getWorkFileTableNameFromDate(planDate);
        Road road = roadService.selectRoadById(roadId);
        String filePath = basePath + "/" + road.getName();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("roadId", roadId);
        queryMap.put("planDate", planDate);
        queryMap.put("tableName", workFileTableNameFromDate);
        List<UserWorkFileVo> userWorkFileVos = userWorkFileService.selectAllByMap(queryMap);
        if (userWorkFileVos.size() > 0) {
            RoadFileUtil.downloadFiles(road.getName(), userWorkFileVos);//下载文件到本地拷贝
            //压缩
            ZipCompressor zipCompressor = new ZipCompressor(filePath + ".zip");
            zipCompressor.compressExe(filePath);
            //下载到客户端
            FileUtil.downLoadFile(filePath + ".zip", response, road.getName());
            //删除文件
            File roadFile = new File(filePath);
            File roadFileZip = new File(filePath + ".zip");
            DeleteDirectory.deleteDir(roadFile);
            if (roadFileZip.exists()) {
                roadFileZip.delete();
            }
            return 1;
        } else {
            return 0;
        }

    }

    /**
     * 核对是否有文件
     *
     * @param roadId
     */
    @RequestMapping("checkHasFile.action")
    @ResponseBody
    public int downLoadFile1(String roadId, String planDate) {
        String workFileTableNameFromDate = StringUtil.getWorkFileTableNameFromDate(planDate);
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("roadId", roadId);
        queryMap.put("planDate", planDate);
        queryMap.put("tableName", workFileTableNameFromDate);
        List<UserWorkFileVo> userWorkFileVos = userWorkFileService.selectAllByMap(queryMap);
        if (userWorkFileVos.size() > 0) {
            return 1;
        } else {
            return 0;
        }

    }

    /**
     * 查询用户分数信息
     *
     * @param searchVo
     * @return
     */
    @RequestMapping("selectUserScore.action")
    @ResponseBody
    public Map<String, Object> selectUserScore(SearchVo searchVo) {
        Map<String, Object> dataMap = new HashMap<>();
        UserTrainScore uts;
        LoginInfo loginInfo = getLoginInfo(searchVo.getLoginId());
        UserTrainScore userTrainScore = new UserTrainScore();
        userTrainScore.setUserNum(loginInfo.getUserNum());
        userTrainScore.setTrainNum(loginInfo.getTrainNum());
        userTrainScore.setPlanTime(loginInfo.getPlanDate());
        userTrainScore.setTrainCode(searchVo.getTrainCode());
        uts = userTrainScoreDao.selectObjectByUserTrainScore(userTrainScore);
        if (uts == null) {
            uts = new UserTrainScore();
            uts.setUserNum(searchVo.getUserNum());
            uts.setTrainCode(searchVo.getTrainCode());
            uts.setPlanTime(searchVo.getStartDate());
            uts.setSysScore(-1);
        }
        String modUser = uts.getModUser();
        if (StringUtil.isEmpty(modUser)) {
            dataMap.put("isMod", 0);
        } else {
            dataMap.put("isMod", 1);
        }
        String todayString2 = DateUtils.getTodayString2("yyyy-MM-dd");
        if (todayString2.equals(searchVo.getStartDate())) {
            dataMap.put("isShow", 0);
        } else {
            dataMap.put("isShow", 1);
        }
        dataMap.put("userTrainScore", uts);
        return dataMap;

    }

    /**
     * 手动更新用户车次分数
     *
     * @param userTrainScore
     * @return
     */
    @RequestMapping(value = "updateUserScore.action")
    @ResponseBody
    public Map<String, Object> updateUserScore(UserTrainScore userTrainScore, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        int code = 0;
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            String userName = user.getUsername();
            userTrainScore.setModUser(userName);
            userTrainScore.setFinalScore(userTrainScore.getModScore());
            try {
                userTrainScoreDao.updateUserTrainScore(userTrainScore);
            } catch (Exception e) {
                e.printStackTrace();
                code = -1;
            }
        } else {
            code = -2;
        }
        resultMap.put("code", code);
        resultMap.put("data", userTrainScore);
        return resultMap;
    }

    /**
     * 查询所有交路
     *
     * @param searchVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllRoads.action")
    public Map<String, Object> selectAllRoads(SearchVo searchVo) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            List<IRoad> iRoads = indexService.selectAllRoads(searchVo);
            Set<IRoad> mapFromIRoads = getMapFromIRoads(iRoads);
            int roadNum = mapFromIRoads.size();
            int userNum = 0;
            for (IRoad mapFromIRoad : mapFromIRoads) {
                userNum += mapFromIRoad.getTrainUserWorkList().get(0).getUsers().size();
            }
            dataMap.put("data", mapFromIRoads);
            dataMap.put("userNum", userNum);
            dataMap.put("roadNum", roadNum);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }

        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 得到set集合
     *
     * @param iRoads
     * @return
     */
    public Set<IRoad> getMapFromIRoads(List<IRoad> iRoads) {
        Map<String, List<ITrainUserWork>> map = new HashMap<>();
        Set<IRoad> newRoads = new LinkedHashSet<>();
        for (IRoad iRoad : iRoads) {
            List<ITrainUserWork> trainUserWorks = map.get(iRoad.getRoadId());
            if (trainUserWorks != null) {
                for (int i = 0; i < trainUserWorks.size(); i++) {
                    try {
                        IUser user = iRoad.getTrainUserWorkList().get(i).getUser();
                        trainUserWorks.get(i).getUsers().add(user);
                    } catch (Exception e) {
                    }
                }
            } else {
                map.put(iRoad.getRoadId(), iRoad.getTrainUserWorkList());
            }
            newRoads.add(iRoad);
        }
        return newRoads;
    }


    /**
     * 查询用户个人的记录
     *
     * @param searchVo
     * @return
     */
    @RequestMapping(value = "selectUserWork.action")
    @ResponseBody
    public Map<String, Object> selectUserWork(SearchVo searchVo) {
        Map<String, Object> resultMap = new HashMap<>();
        int code = 0;
        LoginInfo loginInfo = getLoginInfo(searchVo.getLoginId());
        String tableName = StringUtil.getUserWorkTableNameFromDate(loginInfo.getPlanDate());
        try {
            searchVo.setTableName(tableName);
            List<UserWorkTree> selectAllUserWork = indexDao.selectAllUserWork(searchVo);
            List<FileTypeVo> fileTypeVos = indexDao.selectAllTempWork(loginInfo);
            List<FileTypeVo> fileTypeVos2 = indexDao.selectAllEmergeFile(loginInfo);
            UserWorkUtils.initUserWorkTreeFinishNum(selectAllUserWork);
            List<UserWorkTree> numFromFileVos = UserWorkUtils.getNumFromFileVos(fileTypeVos);
            List<UserWorkTree> numFromFileVos2 = UserWorkUtils.getNumFromEmergeFileVos(fileTypeVos2);
            List<UserWorkTree> numFrom181 = UserWorkUtils.getNumFrom181();
            selectAllUserWork.addAll(numFromFileVos2);
            selectAllUserWork.addAll(numFromFileVos);
            selectAllUserWork.addAll(numFrom181);
            resultMap.put("datas", selectAllUserWork);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        resultMap.put("code", code);
        return resultMap;
    }

    /**
     * 查询用户的上传记录
     *
     * @param searchVo
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "selectAllWorkFile.action")
    @ResponseBody
    public Map<String, Object> selectWorkFile(SearchVo searchVo, HttpServletRequest request, String workId) {
        Map<String, Object> resultMap = new HashMap<>();
        int code = 0;
        LoginInfo loginInfo = getLoginInfo(searchVo.getLoginId());
        String tableName = StringUtil.getWorkFileTableNameFromDate(loginInfo.getPlanDate());
        searchVo.setTableName(tableName);
        searchVo.setUserNum(loginInfo.getUserNum());
        searchVo.setTrainNum(loginInfo.getTrainNum());
        searchVo.setStartDate(loginInfo.getPlanDate());
        try {
            List<WorkFileVo> wfs = new ArrayList<>();
            List<WorkNfc> wnfcs = new ArrayList<>();
            if (StringUtil.isNotEmpty(workId)) {
                List<WorkFileVo> workfiles = (List<WorkFileVo>) request.getSession().getAttribute("workFiles");
                List<WorkNfc> workNfcs = (List<WorkNfc>) request.getSession().getAttribute("workNfcs");
                for (WorkFileVo wfv : workfiles) {
                    String wfId = wfv.getTrainWorkId() + "-" + wfv.getWorkId();
                    if (wfId.contains(workId)) {
                        wfs.add(wfv);
                    }
                }
                for (WorkNfc wn : workNfcs) {
                    String wnId = wn.getTrainWorkId() + "-" + wn.getWorkId();
                    if (wnId.contains(workId)) {
                        wnfcs.add(wn);
                    }
                }
            } else {
                wfs = indexDao.selectAllUserFile(searchVo);
                List<WorkFileVo> mp3Files = indexDao.selectAllUserMp3(searchVo);
                Map<String, WorkFileVo> mp3Map = getMp3Map(mp3Files);
                for (WorkFileVo workFileVo : wfs) {
                    String key = workFileVo.getUserNum() + "-" + workFileVo.getTrainWorkId() + "-" + workFileVo.getWorkId();
                    WorkFileVo mp3File = mp3Map.get(key);
                    workFileVo.setMp3Path(mp3File == null ? "" : mp3File.getFilePath());
                }
                wnfcs = indexDao.selectAllNfc(searchVo);
                request.getSession().setAttribute("workFiles", wfs);
                request.getSession().setAttribute("workNfcs", wnfcs);
            }
            initSimRate(wfs);
            resultMap.put("datas", wfs);
            resultMap.put("nfcDatas", wnfcs);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        resultMap.put("code", code);
        return resultMap;
    }

    /**
     * 初始化相似工序
     *
     * @param workFileVos
     */
    public void initSimRate(List<WorkFileVo> workFileVos) {
        for (WorkFileVo workFileVo : workFileVos) {
            DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
            df.applyPattern("##.##");
            String fileName = workFileVo.getFileName();
            String substring = fileName.substring(13, 17);
            double v = Double.parseDouble(substring) / 100.00;
            if (v > 80) {
                v = v - 20.00;
            }
            if (v < 20) {
                v = v + 10.00;
            }
            if (v < 20) {
                workFileVo.setColorRed("1");
            }
            workFileVo.setSimRate(df.format(v));
        }
    }

    public Map<String, WorkFileVo> getMp3Map(List<WorkFileVo> mp3Files) {
        Map<String, WorkFileVo> map = new HashMap<>();
        for (WorkFileVo mp3File : mp3Files) {
            map.put(mp3File.getUserNum() + "-" + mp3File.getTrainWorkId() + "-" + mp3File.getWorkId(), mp3File);
        }
        return map;
    }
}
